package com.tcm.pay.request;

import cn.hutool.core.util.ObjectUtil;
import com.base.core.utils.R;
import com.tcm.pay.common.HttpRequest;
import com.tcm.pay.domain.dto.ScanPayDTO;
import com.tcm.pay.enums.BusinessCodeEnum;
import com.tcm.pay.util.Base64Util;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;


@Component
public class ScanAliPay implements AggregatePay{


    public Map<String, Object> pay(Object payObject){
        ScanPayDTO scanPayDTO = (ScanPayDTO) payObject;
        if(ObjectUtil.isEmpty(scanPayDTO.getBillNo())){
            R.throwFail(BusinessCodeEnum.BILL_NO_NOT_EXISTS);
        }

        if(ObjectUtil.isEmpty(scanPayDTO.getAmount())){
            R.throwFail(BusinessCodeEnum.AMOUNT_NOT_EXISTS);
        }

        String url = "https://gwapi.yemadai.com/pay/scanpay";

        scanPayDTO.setMerNo("50829");
        scanPayDTO.setPayType("AliJsapiPay_OffLine");
        scanPayDTO.setScanpayMerchantCode("sweep-13206ee0ce3949258d79321eb5b39ba9");
        scanPayDTO.setOrderTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));

        StringBuffer xml = new StringBuffer();
        xml.append("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>");
        xml.append("<ScanPayRequest>");
        xml.append("<MerNo>").append(scanPayDTO.getMerNo()).append("</MerNo>");
        xml.append("<BillNo>").append(scanPayDTO.getBillNo()).append("</BillNo>");
        xml.append("<payType>").append(scanPayDTO.getPayType()).append("</payType>");
        xml.append("<Amount>").append(scanPayDTO.getAmount()).append("</Amount>");
        xml.append("<OrderTime>").append(scanPayDTO.getOrderTime()).append("</OrderTime>");
        xml.append("<ScanpayMerchantCode>").append(scanPayDTO.getScanpayMerchantCode()).append("</ScanpayMerchantCode>");
        xml.append("<AdviceUrl>").append(scanPayDTO.getAdviceUrl()).append("</AdviceUrl>");
        xml.append("<SignInfo>").append(HttpRequest.makeSignForScanPay(scanPayDTO.getMerNo(), scanPayDTO.getBillNo(), scanPayDTO.getAmount(), scanPayDTO.getOrderTime(), scanPayDTO.getAdviceUrl())).append("</SignInfo>");
        xml.append("<products>").append(scanPayDTO.getProducts()).append("</products>");
        xml.append("<remark>").append(scanPayDTO.getRemark()).append("</remark>");
        xml.append("</ScanPayRequest>");
        String xmlData = Base64Util.encode(xml.toString());
        return HttpRequest.postRequestDomain(url, xmlData);
    }


}
